<?php

namespace app\controller;

use app\BaseController;
use app\service\CardService;
use app\service\ImageService;
use think\facade\View;
use think\facade\Request;

/**
 * 名片生成控制器
 */
class CardController extends BaseController
{
    /**
     * 名片服务
     * @var CardService
     */
    protected $cardService;

    /**
     * 图片服务
     * @var ImageService
     */
    protected $imageService;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->cardService = new CardService();
        $this->imageService = new ImageService();
    }

    /**
     * 名片生成页面 - 直接输出HTML绕过模板引擎
     */
    public function index()
    {
        return View::fetch('card/index');
    }

    /**
     * 生成名片数据
     * @return \think\response\Json
     */
    public function generateData()
    {
        try {
            // 获取请求参数
            $params = Request::param();

            // 生成名片数据
            $cardData = $this->cardService->generateCard($params);

            return $this->success($cardData, '生成成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 生成名片图片
     * @return \think\response\Json|void
     */
    public function generateImage()
    {
        try {
            // 获取请求参数
            $params = Request::param();

            // 生成名片数据
            $cardData = $this->cardService->generateCard($params);

            // 创建名片图片
            $imagePath = $this->imageService->createCardImage($cardData);

            return $this->success(['image_path' => $imagePath], '生成成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 查看名片图片
     * @param string $filename 文件名
     */
    public function viewImage($filename = '')
    {
        try {
            // 如果没有传入文件名，从参数中获取
            if (empty($filename)) {
                $filename = Request::param('filename', '');
            }
            
            if (empty($filename)) {
                throw new \Exception('文件名不能为空');
            }
            
            // 输出图片
            $this->imageService->outputImage('/upload/cards/' . $filename);
        } catch (\Exception $e) {
            // 如果图片不存在，返回错误
            header('HTTP/1.1 404 Not Found');
            echo '图片不存在: ' . $e->getMessage();
            exit;
        }
    }

    /**
     * 下载名片图片
     * @param string $filename 文件名
     */
    public function downloadImage($filename = '')
    {
        try {
            // 如果没有传入文件名，从参数中获取
            if (empty($filename)) {
                $filename = Request::param('filename', '');
            }
            
            if (empty($filename)) {
                throw new \Exception('文件名不能为空');
            }
            
            // 构建文件路径
            $imagePath = '/upload/cards/' . $filename;
            $fullPath = __DIR__ . '/../../public' . $imagePath;
            
            // 检查文件是否存在
            if (!file_exists($fullPath)) {
                throw new \Exception('文件不存在');
            }
            
            // 设置下载响应头
            $downloadName = 'business_card_' . date('Y_m_d_H_i_s') . '.png';
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . $downloadName . '"');
            header('Content-Transfer-Encoding: binary');
            header('Content-Length: ' . filesize($fullPath));
            header('Cache-Control: no-cache, no-store, must-revalidate');
            header('Pragma: no-cache');
            header('Expires: 0');
            
            // 输出文件内容
            readfile($fullPath);
            exit;
            
        } catch (\Exception $e) {
            // 如果下载失败，返回错误页面
            header('HTTP/1.1 404 Not Found');
            echo '下载失败: ' . $e->getMessage();
            exit;
        }
    }
}